// 统一的Store工厂
// 提供标准化的Store创建流程，集成所有中间件

import { create, StateCreator } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { persist } from 'zustand/middleware';
import { devtools } from 'zustand/middleware';
import { withCrossModuleSync } from './middleware/crossModuleSync';
import { withPerformanceMonitoring } from './middleware/performanceMonitor';
import { persistenceManager, PersistenceConfig } from './middleware/persistenceManager';

// Store配置接口
export interface StoreConfig {
  name: string;
  version?: number;
  enablePersist?: boolean;
  enableDevtools?: boolean;
  enableSubscribeWithSelector?: boolean;
  enableCrossModuleSync?: boolean;
  enablePerformanceMonitoring?: boolean;
  persistenceConfig?: Partial<PersistenceConfig>;
}

// 基础Store状态接口
export interface BaseStoreState {
  isLoading: boolean;
  error: string | null;
  lastUpdated: number;
  isInitialized: boolean;
}

// 基础Store操作接口
export interface BaseStoreActions {
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  clearError: () => void;
  reset: () => void;
  initialize: () => Promise<void>;
}

// 完整的Store类型
export type BaseStore<T = {}> = BaseStoreState & BaseStoreActions & T;

// Store创建器类型
export type StoreCreator<T> = StateCreator<
  BaseStore<T>,
  [],
  [],
  BaseStore<T>
>;

// 默认配置
const defaultConfig: Required<StoreConfig> = {
  name: 'unnamed-store',
  version: 1,
  enablePersist: true,
  enableDevtools: process.env.NODE_ENV === 'development',
  enableSubscribeWithSelector: true,
  enableCrossModuleSync: true,
  enablePerformanceMonitoring: process.env.NODE_ENV === 'development',
  persistenceConfig: {},
};

// 创建基础状态
export const createBaseState = (): BaseStoreState => ({
  isLoading: false,
  error: null,
  lastUpdated: Date.now(),
  isInitialized: false,
});

// 创建基础操作
export const createBaseActions = <T>(
  set: (partial: any) => void,
  get: () => BaseStore<T>
): BaseStoreActions => ({
  setLoading: (loading: boolean) => {
    set({ isLoading: loading, lastUpdated: Date.now() });
  },

  setError: (error: string | null) => {
    set({ error, lastUpdated: Date.now() });
  },

  clearError: () => {
    set({ error: null, lastUpdated: Date.now() });
  },

  reset: () => {
    set({
      ...createBaseState(),
      isInitialized: false,
    });
  },

  initialize: async () => {
    const state = get();
    if (state.isInitialized) return;

    set({ isLoading: true, error: null });

    try {
      // 子类可以重写这个方法来实现自定义初始化逻辑
      await new Promise(resolve => setTimeout(resolve, 100));
      
      set({ 
        isInitialized: true, 
        isLoading: false, 
        lastUpdated: Date.now() 
      });
    } catch (error) {
      set({ 
        isLoading: false, 
        error: error instanceof Error ? error.message : 'Initialization failed',
        lastUpdated: Date.now() 
      });
    }
  },
});

// 主要的Store工厂函数
export const createStore = <T>(
  storeCreator: (
    set: (partial: any) => void,
    get: () => BaseStore<T>,
    store: any
  ) => BaseStore<T>,
  config: StoreConfig
) => {
  const finalConfig = { ...defaultConfig, ...config };
  
  // 构建中间件链
  let creator: StateCreator<BaseStore<T>, [], [], BaseStore<T>> = storeCreator;

  // 1. 性能监控中间件（最内层，直接包装原始creator）
  if (finalConfig.enablePerformanceMonitoring) {
    creator = withPerformanceMonitoring(creator, finalConfig.name);
  }

  // 2. 跨模块同步中间件
  if (finalConfig.enableCrossModuleSync) {
    creator = withCrossModuleSync(creator, finalConfig.name);
  }

  // 3. 订阅选择器中间件
  if (finalConfig.enableSubscribeWithSelector) {
    creator = subscribeWithSelector(creator);
  }

  // 4. 持久化中间件
  if (finalConfig.enablePersist) {
    const persistConfig = persistenceManager.createPersistConfig({
      name: finalConfig.name,
      version: finalConfig.version,
      ...finalConfig.persistenceConfig,
    });
    creator = persist(creator, persistConfig);
  }

  // 5. 开发工具中间件（最外层）
  if (finalConfig.enableDevtools) {
    creator = devtools(creator, {
      name: finalConfig.name,
      enabled: process.env.NODE_ENV === 'development',
    });
  }

  return create(creator);
};

// 简化的Store创建函数（使用默认配置）
export const createSimpleStore = <T>(
  storeCreator: (
    set: (partial: any) => void,
    get: () => BaseStore<T>
  ) => BaseStore<T>,
  name: string
) => {
  return createStore(
    (set, get) => ({
      ...createBaseState(),
      ...createBaseActions(set, get),
      ...storeCreator(set, get),
    }),
    { name }
  );
};

// 创建只读Store（不包含基础操作）
export const createReadonlyStore = <T>(
  storeCreator: (
    set: (partial: any) => void,
    get: () => T
  ) => T,
  config: StoreConfig
) => {
  return create<T>(storeCreator);
};

// Store组合工具
export const combineStores = <T extends Record<string, any>>(
  stores: T
): T => {
  return stores;
};

// Store选择器工具
export const createSelector = <T, R>(
  selector: (state: T) => R,
  equalityFn?: (a: R, b: R) => boolean
) => {
  return selector;
};

// Store订阅工具
export const subscribeToStore = <T>(
  store: any,
  selector: (state: T) => any,
  callback: (selectedState: any, previousSelectedState: any) => void
) => {
  if (store.subscribe) {
    return store.subscribe(selector, callback);
  }
  throw new Error('Store does not support subscription');
};

// Store调试工具
export const debugStore = <T>(store: any, storeName: string) => {
  if (process.env.NODE_ENV === 'development') {
    // 添加调试信息
    console.group(`🏪 Store Debug: ${storeName}`);
    console.log('Current State:', store.getState());
    console.log('Store Methods:', Object.keys(store.getState()));
    console.groupEnd();

    // 监听状态变化
    if (store.subscribe) {
      store.subscribe((state: T) => {
        console.log(`🔄 ${storeName} State Changed:`, state);
      });
    }
  }
};

// Store性能分析工具
export const analyzeStorePerformance = (storeName: string) => {
  if (process.env.NODE_ENV === 'development') {
    const { performanceMonitor } = require('./middleware/performanceMonitor');
    const metrics = performanceMonitor.getMetrics(storeName);
    
    if (metrics) {
      console.group(`📊 Store Performance: ${storeName}`);
      console.log('Update Count:', metrics.stateUpdateCount);
      console.log('Average Update Time:', `${metrics.averageUpdateTime.toFixed(2)}ms`);
      console.log('Max Update Time:', `${metrics.maxUpdateTime.toFixed(2)}ms`);
      console.log('Memory Usage:', `${(metrics.memoryUsage / 1024 / 1024).toFixed(2)}MB`);
      
      const suggestions = performanceMonitor.getOptimizationSuggestions(storeName);
      if (suggestions.length > 0) {
        console.log('Optimization Suggestions:', suggestions);
      }
      
      console.groupEnd();
    }
  }
};

// Store健康检查工具
export const healthCheckStore = <T>(store: any, storeName: string): {
  isHealthy: boolean;
  issues: string[];
  suggestions: string[];
} => {
  const issues: string[] = [];
  const suggestions: string[] = [];

  try {
    const state = store.getState();
    
    // 检查基础状态
    if (typeof state !== 'object' || state === null) {
      issues.push('State is not an object');
    }

    // 检查错误状态
    if (state.error) {
      issues.push(`Store has error: ${state.error}`);
      suggestions.push('Clear the error state or handle the error properly');
    }

    // 检查加载状态
    if (state.isLoading) {
      suggestions.push('Store is in loading state, ensure loading is properly managed');
    }

    // 检查初始化状态
    if (!state.isInitialized) {
      suggestions.push('Store is not initialized, call initialize() method');
    }

    // 检查状态大小
    const stateSize = JSON.stringify(state).length;
    if (stateSize > 1024 * 1024) { // 1MB
      issues.push('State size is too large (>1MB)');
      suggestions.push('Consider state normalization or data cleanup');
    }

  } catch (error) {
    issues.push(`Failed to access store state: ${error}`);
  }

  return {
    isHealthy: issues.length === 0,
    issues,
    suggestions,
  };
};

// 导出类型和工具
export type { StoreConfig, BaseStoreState, BaseStoreActions, BaseStore };
export {
  defaultConfig,
  persistenceManager,
};
